package com.chuangjiangx.member.score.ddd.application;

import com.chuangjiangx.commons.JacksonUtils;
import com.chuangjiangx.commons.exception.BaseException;
import com.chuangjiangx.member.score.ddd.application.command.ClaimCodeValidationCommand;
import com.chuangjiangx.member.score.ddd.application.result.ClaimCodeValidationResult;
import com.chuangjiangx.member.score.ddd.domain.model.MbrScoreGiftRecord;
import com.chuangjiangx.member.score.ddd.domain.repository.MbrScoreGiftRecordRepository;
import com.chuangjiangx.member.score.ddd.domain.model.MbrScoreGiftRule;
import com.chuangjiangx.member.score.ddd.domain.repository.MbrScoreGiftRuleRepository;
import com.chuangjiangx.member.score.ddd.domain.event.ClaimCodeExchangeEvent;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author cj-ch
 * @date 2018/7/4 下午6:35
 */
@Service
public class MbrScoreGiftRecordApplication {

    @Autowired
    private MbrScoreGiftRecordRepository mbrScoreGiftRecordRepository;
    @Autowired
    private MbrScoreGiftRuleRepository mbrScoreGiftRuleRepository;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 取货码核销
     * @param command
     */
    public ClaimCodeValidationResult validation(ClaimCodeValidationCommand command){
        MbrScoreGiftRecord mbrScoreGiftRecord = mbrScoreGiftRecordRepository.fromClaimCode(command.getClaimCode(),command.getMerchantId());
        if(null == mbrScoreGiftRecord){
            throw new BaseException("","兑换记录不存在");
        }
        MbrScoreGiftRule mbrScoreGiftRule = mbrScoreGiftRuleRepository.fromId(mbrScoreGiftRecord.getMbrScoreGiftRuleId());
        if(null == mbrScoreGiftRule){
            throw new BaseException("","积分兑换规则不存在");
        }
        if(!Objects.equals(mbrScoreGiftRecord.getMerchantId().getId(),command.getMerchantId())){
            throw new BaseException("","不可跨商户操作");
        }

        mbrScoreGiftRecord.claimGoods(command.getStoreId(),command.getStoreUserId(),command.getMerchantUserId());
        mbrScoreGiftRecordRepository.update(mbrScoreGiftRecord);
        //发送会员取货码核销Redis订阅消息
        ClaimCodeExchangeEvent exchangeEvent = new ClaimCodeExchangeEvent(
                mbrScoreGiftRecord.getMemberId().getId(),
                mbrScoreGiftRecord.getClaimCode(),
                mbrScoreGiftRecord.getClaimTime()
        );
        redisTemplate.convertAndSend("claimcode_use_success",JacksonUtils.toJson(objectMapper,exchangeEvent));
        return new ClaimCodeValidationResult(
                mbrScoreGiftRule.getId().getId(),
                mbrScoreGiftRule.getName(),
                mbrScoreGiftRule.getGoodsName(),
                mbrScoreGiftRule.getGoodsPrice(),
                mbrScoreGiftRule.getImageUrl()
        );
    }
}
